/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.jdbc.log;

import cn.jfast.framework.log.LogFactory;
import cn.jfast.framework.log.LogType;
import cn.jfast.framework.log.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class SqlLogger implements InvocationHandler{

	private Logger log = LogFactory.getLogger(LogType.JFast,SqlLogger.class);
	private List<Object> params = new ArrayList<Object>();
	private String targetDao = "";
	private String sql = "";
    private java.sql.PreparedStatement ps;
    private boolean noLog = false;

    public SqlLogger(java.sql.PreparedStatement ps, String sql, String targetDao, boolean noLog){
    	this.ps = ps;
		this.sql = sql;
		this.targetDao = targetDao;
		this.noLog = noLog;
    }

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		try {
			if (method.getName().startsWith("setObject")
					||method.getName().startsWith("setString")) {
				params.add(args[1]);
			} else if(method.getName().startsWith("setNull")) {
				params.add(null);
			} else if (method.getName().startsWith("executeQuery")) {
				if(!noLog)
					log.info("\n数据接口 : %s\n查询语句: %s\n ",targetDao+"()",String.format(sql, params.toArray()));
			} else if (method.getName().startsWith("execute")) {
				if(!noLog)
					log.info("\n数据接口 : %s\n更新语句 : %s\n ",targetDao+"()",String.format(sql, params.toArray()));
			}
			return method.invoke(ps, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}
}
